package cn.ysym.tcsy;

import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.ysym.dao.ProductDao;
import cn.ysym.dao.SettingDao;
import cn.ysym.dao.ShippingMoveDao;
import cn.ysym.model.Setting;
import cn.ysym.model.ShippingMove;
import cn.ysym.util.CommonUtil;
import cn.ysym.util.HttpUtil;
import cn.ysym.util.VibratorUtil;

/**
 * @author zhou
 * @createTime 2021-11-05 9:04
 */
public class OnlineShippingMoveActivity extends AppCompatActivity {

    @BindView(R.id.etMove)
    EditText etMove;
    @BindView(R.id.lvMove)
    ListView lvMove;
    @BindView(R.id.etDealer)
    EditText etDealer;
    @BindView(R.id.etCode)
    EditText etCode;
    @BindView(R.id.lvData)
    ListView lvData;

    private boolean taskDoing = false;
    private SettingDao settingDao;
    private ProductDao productDao;
    private ProgressBar progressBar;
    private DownloadTask downloadTask;
    private UpDataTask upDataTask;
    private TextView tvResult;
    private Button bShippingFinish;
//    private SharedPreferences setting;
    private ShippingMoveDao shippingMoveDao;

    private String serverUrl;
    private int moveId;



    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_online_shippingmove);
        ButterKnife.bind(this); //绑定butterKnife插件
        setTitle("在线调货");


//        setting = getSharedPreferences("setInfo", MODE_PRIVATE);
        tvResult = findViewById(R.id.tvResult);
        bShippingFinish = findViewById(R.id.bShippingFinish);
        settingDao = new SettingDao(this);
        shippingMoveDao = new ShippingMoveDao(this);
        doDownload();
        shippingMoveDao.clearAll();
        etCode.requestFocus();
        etDealer.setEnabled(false);

//        etMove.setOnClickListener(view -> {
//            ArrayAdapter<String> dealerAdapter = new ArrayAdapter<>(OnlineShippingMoveActivity.this, R.layout.list_view);
//            List<ShippingMove> moveList = shippingMoveDao.query("");
//            for (ShippingMove p : moveList) {
//                dealerAdapter.add(p.getMoveId() + " " + p.getToDealerName());
//            }
//            lvMove.setAdapter(dealerAdapter);
//            lvMove.setVisibility(View.VISIBLE);
//        });
        etMove.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean hasFocus) {
                if(hasFocus){
                    ArrayAdapter<String> moveNumAdapter = new ArrayAdapter<String>(OnlineShippingMoveActivity.this,R.layout.list_view);
                    List<ShippingMove> moveList = shippingMoveDao.query("");
                    for(ShippingMove move : moveList){
                        moveNumAdapter.add(CommonUtil.formatStr(move.getMoveId()+" "+move.getToDealerName()));
                    }
                    lvMove.setAdapter(moveNumAdapter);
                    lvMove.setVisibility(View.VISIBLE);
                }
            }
        });

        etMove.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }



            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                ArrayAdapter<String> moveNumAdapter = new ArrayAdapter<String>(OnlineShippingMoveActivity.this,R.layout.list_view);
                List<ShippingMove> moveList = shippingMoveDao.query("");
                for(ShippingMove move : moveList){
                    moveNumAdapter.add(CommonUtil.formatStr(move.getMoveId()+" "+move.getToDealerName()));
                }
                lvMove.setAdapter(moveNumAdapter);
            }
        });

        lvMove.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String text = parent.getAdapter().getItem(position).toString();
                String dataId = CommonUtil.getDataId(text);
                String dataBack = CommonUtil.getDataBack(text);
                etMove.setText(dataId);
                etDealer.setText(dataBack);
                moveId = Integer.parseInt(dataId);
                lvMove.setVisibility(View.GONE);
                etCode.requestFocus();
            }
        });

        etCode.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
                    String code = etCode.getText().toString();
                    String mId = etMove.getText().toString();
                    if (CommonUtil.isEmpty(mId)) {
                        VibratorUtil.vibrate(getApplicationContext(), VibratorUtil.milliSeconds);
                        Toast.makeText(getApplicationContext(), "请选择调货单号", Toast.LENGTH_SHORT).show();
                        etCode.setText("");
                        etMove.requestFocus();
                        return true;
                    }
                    if (CommonUtil.isEmpty(code)) {
                        VibratorUtil.vibrate(getApplicationContext(), VibratorUtil.milliSeconds);
                        Toast.makeText(getApplicationContext(), "请扫码后提交", Toast.LENGTH_SHORT).show();
                        return true;
                    }
                    code = CommonUtil.cleanCode(code);
                    moveId = Integer.parseInt(mId);
                    upDataTask = new UpDataTask(code, moveId, false);
                    upDataTask.execute((Void) null);
                    return true;
                }
                return false;
            }
        });

        bShippingFinish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //弹出退出确认框
                new AlertDialog.Builder(OnlineShippingMoveActivity.this)
                        .setTitle("系统提示")
                        .setMessage("确认调货完成？")
                        .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                taskDoing = true;
//                                progressBar.setVisibility(View.VISIBLE);
                                upDataTask = new UpDataTask("", moveId, true);
                                upDataTask.execute((Void) null);
                                GetShippingMoveDetailTask task = new GetShippingMoveDetailTask();
                                task.execute((Void) null);
                            }
                        }).setNegativeButton("取消",null).show();
            }
        });
    }

    //后台上传数据
    public class UpDataTask extends AsyncTask<Void, Void, String> {

        private String code;
        private int moveId;
        private boolean commit;

        public UpDataTask(String code, int moveId, boolean commit) {
            this.code = code;
            this.moveId = moveId;
            this.commit = commit;
        }

        @Override
        protected String doInBackground(Void... voids) {
            JSONObject req = new JSONObject();
            try {

                String reqUrl = "upShippingMoveDataNew.sdo";
                Setting userName = settingDao.query("userName");
                Setting sessionKey = settingDao.query("sessionKey");
                req.put("account",userName.getSettingValue());
                req.put("moveId",moveId);
                if (commit) {
                    reqUrl = "commitShippingMoveData.sdo";
                } else {
                    req.put("code", code);
                }
                req.put("sign",HttpUtil.genSign(req,sessionKey.getSettingValue()));
                String ret = HttpUtil.postJson(reqUrl,req.toString());
                return ret;
            } catch (Exception e) {
                Log.d("zqfw", e.getMessage() + "");
            }

            return null;
        }

        @Override
        protected void onPostExecute(final String retStr) {
            upDataTask = null;
            if (retStr != null) {
                try {
                    JSONObject retJson = new JSONObject(retStr);
                    if (retJson.getInt("result") == 1) {
                        System.out.println("后台上传数据成功");
                        GetShippingMoveDetailTask task = new GetShippingMoveDetailTask();
                        task.execute((Void) null);
                        String msg = retJson.getString("message");
                        tvResult.setText(msg);
                    } else {
                        VibratorUtil.vibrate(getApplicationContext(), VibratorUtil.milliSeconds);
                        String msg = retJson.getString("message");
                        Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
                        tvResult.setText(msg);
                    }
                } catch (JSONException e) {
                    Log.d("zqfw", e.getMessage() + "");   //当msg为null时就会报NullPointerException: println needs a message
                }
            } else {
                VibratorUtil.vibrate(getApplicationContext(), VibratorUtil.milliSeconds);
                Toast.makeText(getApplicationContext(), "失败，请确认已连接网络", Toast.LENGTH_SHORT).show();
            }
            etCode.setText("");
            etCode.requestFocus();
        }

    }

    //获取调货详情
    public class GetShippingMoveDetailTask extends AsyncTask<Void, Void, String> {
        private String message = "对不起，服务异常！";

        public GetShippingMoveDetailTask() {

        }

        @Override
        protected String doInBackground(Void... params) {
            JSONObject req = new JSONObject();
            try {
                Setting userName = settingDao.query("userName");
                Setting sessionKey = settingDao.query("sessionKey");
                req.put("version", CommonUtil.getSoftVersion());
                req.put("account", userName.getSettingValue());
                req.put("sign", HttpUtil.genSign(req, sessionKey.getSettingValue()));
                String retStr = HttpUtil.postJson("getShippingMoveDetail.sdo", req.toString());
                return retStr;
            } catch (Exception e) {
                message = e.getMessage();
            }
            return null;
        }

        @Override
        protected void onPostExecute(final String retStr) {
            taskDoing = false;
//            progressBar.setVisibility(View.GONE);
            if (retStr != null) {
                try {
                    int isNull = 1;
                    JSONObject retJson = new JSONObject(retStr);
                    JSONArray data = retJson.getJSONArray("data");
                    List<HashMap<String, Object>> listData = new ArrayList<>();
                    for (int i = 0; i < data.length(); i++) {
                        JSONObject item = data.getJSONObject(i);
                        HashMap<String, Object> oneData = new HashMap<>();
                        String productName = item.getString("productName");
                        String bigNum = item.getString("bigNumber");
                        String midNum = item.getString("middleNumber");
                        String sanNum = item.getString("sanNumber");
                        oneData.put("productName", productName);
                        oneData.put("bigNumber", bigNum);
                        oneData.put("middleNumber", midNum);
                        oneData.put("sanNumber", sanNum);
                        listData.add(oneData);
                    }
                    if(data.length()>0){
                        isNull = 0 ;
                    }
                    SimpleAdapter adapter = new SimpleAdapter(OnlineShippingMoveActivity.this, listData, R.layout.shipping_data_item,
                            new String[]{"productName", "bigNumber", "middleNumber", "sanNumber"}, new int[]{R.id.tvProductId, R.id.tvProductName, R.id.tvSendNum, R.id.tvSentNum});
                    lvData.setAdapter(adapter);

                    if (retJson.getInt("status") != 200) {
                        message = retJson.getString("message");
                        VibratorUtil.vibrate(getApplicationContext(), VibratorUtil.milliSeconds);
                        Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
                        tvResult.setText(message);
                    }else{
                        message = retJson.getString("message");
                        if(isNull == 0){
                            Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
                            tvResult.setText(message);
                        }else{
                            Toast.makeText(getApplicationContext(), "成功", Toast.LENGTH_SHORT).show();
                            tvResult.setText("成功");
                        }
                    }
                } catch (JSONException e) {
                    message = e.getMessage();
                }
            } else {
                VibratorUtil.vibrate(getApplicationContext(), VibratorUtil.milliSeconds);
                Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
            }
        }
    }

    //下载调货单号数据
    protected void doDownload() {
        if (downloadTask != null) {
            return;
        }
        downloadTask = new DownloadTask();
        downloadTask.execute((Void) null);
    }

    //下载调货单号数据
    public class DownloadTask extends AsyncTask<Void, Void, Boolean> {
        @Override
        protected Boolean doInBackground(Void... params) {
            JSONObject req = new JSONObject();
            try {
                Setting userName = settingDao.query("userName");
                Setting sessionKey = settingDao.query("sessionKey");
                req.put("account", userName.getSettingValue());
                req.put("sign", HttpUtil.genSign(req, sessionKey.getSettingValue()));
                String retStr = HttpUtil.postJson( "getShippingMoveList.sdo", req.toString());
                JSONObject retJson = new JSONObject(retStr);
                if (retJson.getInt("result") == 1) {
                    //调货单号数据
                    shippingMoveDao.clearAll();
                    JSONArray moveList = retJson.getJSONArray("moveList");
                    System.out.println(moveList);
                    for (int i = 0; i < moveList.length(); i++) {
                        JSONObject shippingMove = moveList.getJSONObject(i);
                        if (shippingMove.has("moveId")) {
                            ShippingMove model = new ShippingMove();
                            model.setMoveId(shippingMove.getInt("moveId"));
                            model.setToDealerName(shippingMove.getString("toDealerName"));
                            shippingMoveDao.insert(model);
                        }
                    }

                    return true;
                }
            } catch (Exception e) {
                Log.d("zqfw", e.getMessage());
            }

            return false;
        }

        @Override
        protected void onPostExecute(final Boolean success) {
            downloadTask = null;
            if (success) {
                Toast.makeText(getApplicationContext(), "调货单号数据下载完成！",
                        Toast.LENGTH_SHORT).show();
            }
            else {
                VibratorUtil.vibrate(getApplicationContext(), VibratorUtil.milliSeconds);
//                createDialog("调货单号下载失败，请核对账号及网络", 0);
                Toast.makeText(getApplicationContext(), "调货单号下载失败，请核对账号及网络！",
                        Toast.LENGTH_SHORT).show();
            }
        }

    }
}
